# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from json.encoder import JSONEncoder
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render_to_response
from job_manager.models import Feed
from job_manager.services.logs_service import read_log, get_feed_logs_file_names
from job_manager.utils.logging_utils import getlogger

__author__ = 'irudakov'

LOG = getlogger(__name__)

def get_logs(request):
    log_content = {}
    if request.is_ajax():
        feed_id, log_file_name, start_byte = request.GET.get("feed_id"), request.GET.get("log_file_name"), request.GET.get("start_byte")
        if log_file_name != 'fake':
            log_content = read_log(feed_id, log_file_name, start_byte)
    json_response = JSONEncoder().encode(log_content)
    return HttpResponse(json_response, mimetype="application/javascript")

@login_required
def feed_logs(request, feed_id):
    try:
        feed = Feed.objects.get(id=feed_id)
        log_files = get_feed_logs_file_names(feed)
        return render_to_response("feed_logs.html", {"log_files":log_files, "feed_id":feed_id, "feed_name":feed.name})
    except ObjectDoesNotExist:
        LOG.debug("Couldn't get job logs because it wasn't found. Job id: %s" % feed_id)
        return render_to_response("feed_logs.html", {"log_files":None, "feed_id":None, "feed_name":"Job wasn't found. Sorry..."})